import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yp/config/index.dart';
import 'package:yp/router.dart';
import 'package:yp/util/util.dart';
import 'package:yp/widgets/bottom_sheet.dart';
import 'package:yp/widgets/index.dart';
import 'package:get/get.dart';
import 'package:yp/widgets/shop.dart';

/// 购物车UI
class Trolley extends StatefulWidget {
  final bool showBack;
  const Trolley({Key key, this.showBack}) : super(key: key);

  @override
  _TrolleyState createState() => _TrolleyState();
}

class _TrolleyState extends State<Trolley>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  AnimationController _controller;

  List _goodsSourceList = [
    {'isSelect': true},
    {'isSelect': false},
    {'isSelect': false},
    {'isSelect': false},
    {'isSelect': false, 'expire': true}
  ];
  List _expireSourceList = [
    {'expire': true},
    {'expire': true}
  ];

  List<Map<String, dynamic>> _specificationList = [
    {
      'id': '1',
      'name': '规格',
      'list': [
        {'id': '1', 'name': '规格1', 'isSelect': false},
        {'id': '2', 'name': '规格2', 'isSelect': false},
        {'id': '3', 'name': '规格3', 'isSelect': false},
        {'id': '4', 'name': '规格4', 'isSelect': false},
        {'id': '5', 'name': '规格5', 'isSelect': false},
        {'id': '6', 'name': '规格6', 'isSelect': false},
        {'id': '7', 'name': '规格7', 'isSelect': false},
        {'id': '8', 'name': '规格8很长很长足够长非常的长', 'isSelect': false}
      ]
    },
    {
      'id': '2',
      'name': '型号',
      'list': [
        {'id': '1', 'name': '型号1型号1型号1型号1', 'isSelect': false},
        {'id': '2', 'name': '型号2', 'isSelect': false},
        {'id': '3', 'name': '型号3型号3型号3型号3', 'isSelect': false},
        {'id': '4', 'name': '型号4', 'isSelect': false}
      ]
    },
    {
      'id': '3',
      'name': '样式',
      'list': [
        {'id': '1', 'name': '样式1', 'isSelect': false},
        {'id': '2', 'name': '样式2', 'isSelect': false},
        {'id': '3', 'name': '样式3', 'isSelect': false},
        {'id': '4', 'name': '样式4', 'isSelect': false},
        {'id': '5', 'name': '样式5', 'isSelect': false},
        {'id': '6', 'name': '样式6', 'isSelect': false}
      ]
    }
  ];

  /// 全选
  bool _selectAll = false;

  /// 编辑
  bool _edit = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: YPNavigationBar(
        '购物车',
        backgroundColor: EsColors.White,
        showBack: widget?.showBack ?? false,
        titleColor: EsColors.TitleSecondary,
        actions: [
          TextButton(
            onPressed: () {},
            child: TextButton(
              onPressed: () {
                toast('编辑');
                setState(() {
                  _edit = !_edit;
                });
              },
              child: Text(
                _edit ? '完成' : '编辑',
                style: TextStyle(
                    color: EsColors.TitleSecondary,
                    fontSize: EsSizes.MD,
                    fontWeight: EsFontWeights.Normal),
              ),
            ),
          )
        ],
      ),
      body: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.only(bottom: 55),
            child: CustomScrollView(
              slivers: <Widget>[
                SliverToBoxAdapter(
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        // _tips('全网满减', '购满168元立减20元', EsColors.Primary,
                        //     EsColors.Primary.withOpacity(0.2)),
                        _list(),
                        _expireGoodsList()
                      ]),
                )
              ],
            ),
          ),
          Positioned(bottom: 0, left: 0, right: 0, child: _bottom())
        ],
      ),
      backgroundColor: EsColors.White,
    );
  }

  /// 满减tips
  Widget _tips(String tips, String info, Color tipsColor, Color bgColor,
      {bool visible = true, double left = 10}) {
    return Visibility(
      visible: visible,
      child: Container(
          color: bgColor,
          padding: EdgeInsets.fromLTRB(left, 12, 10, 12),
          child: Row(
            children: [
              Container(
                  padding: const EdgeInsets.fromLTRB(4, 1, 4, 2),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: tipsColor,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Text(
                    tips,
                    style: TextStyle(
                        color: EsColors.White,
                        fontSize: EsSizes.XXS,
                        fontWeight: EsFontWeights.Normal),
                  )),
              SizedBox(width: 4),
              Expanded(
                child: Text(
                  info,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: EsColors.TitleSecondary,
                      fontSize: EsSizes.SM,
                      fontWeight: EsFontWeights.Normal),
                ),
              )
            ],
          )),
    );
  }

  /// 商品list
  Widget _list() {
    return Column(
      children: [
        ShopName('平台自营'),
        YpLine(),
        ListView.separated(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) => _goods(_goodsSourceList[index]),
            separatorBuilder: (context, index) => YpLine(),
            itemCount: _goodsSourceList?.length),
        YpLine(thickness: 20, height: 20, color: Color(0xffededed)),
        ShopName('陆家嘴尚悦湾总店(营业中)'),
        YpLine(),
        ListView.separated(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) => _goods(_goodsSourceList[index]),
            separatorBuilder: (context, index) => YpLine(),
            itemCount: _goodsSourceList?.length),
        YpLine(thickness: 20, height: 20, color: Color(0xffededed)),
      ],
    );
  }

  /// 商品信息item
  Widget _goods(Map info) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        _tips('满减', '生鲜水果每满199减20，还差15元', EsColors.Primary, EsColors.White,
            visible: true),
        YpLine(indent: 8),
        Padding(
          padding: const EdgeInsets.only(left: 8.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(width: 8),
              Expanded(
                child: Column(
                  children: [
                    _goodsInfo(info['isSelect']),
                    YpLine(indent: 58.w),
                    _integral(),
                    YpLine(indent: 58.w),
                    _gift(info['isSelect'] ?? false)
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 主商品信息
  Widget _goodsInfo(bool isSelect) {
    return Row(
      children: [
        GestureDetector(
          onTap: () {
            setState(() {
              isSelect = !isSelect;
            });
            print(isSelect ? '选中' : '取消');
          },
          child: Image(
            image: AssetImage(isSelect
                ? 'assets/images/selectIcon1.png'
                : 'assets/images/select1.png'),
            width: 48.w,
          ),
        ),
        CachedImage(
            width: 80,
            height: 80,
            margin: EdgeInsets.fromLTRB(0, 10, 8, 12),
            scale: BoxFit.cover,
            path:
                'http://imgservice.suning.cn/uimg1/b2c/image/LbK15Wx6ONCA2R1lpJXkOg.jpg_800w_800h_4e'),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(
                '方太（FOTILE）CXW-258-JC7...',
                style: TextStyle(
                    color: EsColors.TitleSecondary,
                    fontSize: EsSizes.MD,
                    fontWeight: EsFontWeights.Normal),
              ),
              GestureDetector(
                onTap: () {
                  print('选择其他规格');
                  //   YpBottomSheet.showSpecification(context, _specificationList,
                  //     (selectIndex, selectString, {info}) {
                  //   print(info);
                  // });
                },
                behavior: HitTestBehavior.opaque,
                child: Container(
                  padding:
                      const EdgeInsets.symmetric(vertical: 1, horizontal: 6),
                  margin: const EdgeInsets.fromLTRB(0, 6, 0, 8),
                  constraints: BoxConstraints(
                      maxWidth: MediaQuery.of(context).size.width / 3),
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Color(0xFFDDDDDD),
                      width: 1,
                    ),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          '22超大风量+挥手智控...',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: EsColors.Content,
                              fontSize: EsSizes.XXS,
                              fontWeight: EsFontWeights.Normal),
                        ),
                      ),
                      Icon(
                        Icons.expand_more,
                        size: 14,
                        color: EsColors.Content,
                      )
                    ],
                  ),
                ),
              ),
              Row(
                children: [
                  Expanded(
                    child: RichText(
                      // textAlign: TextAlign.center,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      text: TextSpan(
                          text: '￥',
                          style: TextStyle(
                              fontSize: EsSizes.XXS,
                              color: EsColors.Primary,
                              fontWeight: EsFontWeights.Normal),
                          children: <TextSpan>[
                            TextSpan(
                                text: '429990.00',
                                style: TextStyle(
                                    fontSize: EsSizes.LG,
                                    color: EsColors.Primary,
                                    fontWeight: EsFontWeights.Medium)),
                          ]),
                    ),
                  ),
                  IconButton(
                      onPressed: () {
                        print('sub');
                      },
                      icon: Image(
                        image: AssetImage("assets/images/reduce.png"),
                        width: 48.w,
                      )),
                  Text('1',
                      style: TextStyle(
                          fontSize: EsSizes.LG,
                          color: EsColors.TitleSecondary,
                          fontWeight: EsFontWeights.Normal)),
                  IconButton(
                      onPressed: () {
                        print('add');
                      },
                      icon: Image(
                        image: AssetImage("assets/images/plus.png"),
                        width: 48.w,
                      )),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 积分
  Widget _integral() {
    return Padding(
      padding: EdgeInsets.only(left: 58.w),
      child: Row(
        children: [
          Text('积分优惠',
              style: TextStyle(
                  fontSize: EsSizes.XS,
                  color: EsColors.TitleSecondary,
                  fontWeight: EsFontWeights.Medium)),
          Expanded(
              child: Text('  使用20积分可享用20积分可享用20积分可享受优惠价29.9元',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      fontSize: EsSizes.XS,
                      color: EsColors.TitleSecondary,
                      fontWeight: EsFontWeights.Normal))),
          Text('积分不足',
              style: TextStyle(
                  fontSize: EsSizes.XS,
                  color: EsColors.Pink,
                  fontWeight: EsFontWeights.Normal)),
          TextButton(
              style: TextButton.styleFrom(
                  minimumSize: Size(32, 22), padding: EdgeInsets.zero),
              onPressed: () {
                print('参加');
              },
              child: Text(
                '参加',
                style: TextStyle(
                    fontSize: EsSizes.XS,
                    color: Colors.orange,
                    fontWeight: EsFontWeights.Normal),
              ))
        ],
      ),
    );
  }

  /// 赠品信息
  Widget _gift(bool more) {
    return more
        ? _tips('赠品', '原装】方太JCD1/JCD6/JCD9适配3D免清洁滤油网', Colors.orange,
            EsColors.White,
            left: 58.w)
        : Padding(
            padding: EdgeInsets.only(top: 4, bottom: 10, right: 12, left: 58.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(
                  '赠品',
                  style: TextStyle(
                      color: EsColors.TitleSecondary,
                      fontSize: EsSizes.XS,
                      fontWeight: EsFontWeights.Medium),
                ),
                SizedBox(width: 6),
                Expanded(
                  child: ListView.builder(
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: 2,
                      itemBuilder: (context, index) {
                        return Row(
                          children: [
                            Expanded(
                              child: Text(
                                '曼秀雷敦护肤剂试用装曼秀雷敦护肤剂试用装曼秀雷敦护肤剂试用装曼秀雷敦护肤剂试用装',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    color: EsColors.TitleSecondary,
                                    fontSize: EsSizes.XS,
                                    fontWeight: EsFontWeights.Normal),
                              ),
                            ),
                            SizedBox(width: 4),
                            Text(
                              'x2',
                              maxLines: 1,
                              style: TextStyle(
                                  color: EsColors.TitleSecondary,
                                  fontSize: EsSizes.XS,
                                  fontWeight: EsFontWeights.Normal),
                            )
                          ],
                        );
                      }),
                )
              ],
            ),
          );
  }

  /// 失效商品部分
  Widget _expireGoodsList() {
    return Visibility(
      visible: _expireSourceList?.isNotEmpty ?? false,
      child: Column(children: [
        ShopName('失效商品', showIcon: false),
        YpLine(),
        ListView.separated(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) => _expireGoods(),
            separatorBuilder: (context, index) => YpLine(indent: 48),
            itemCount: _expireSourceList?.length),
        YpLine(indent: 48),
        OutlinedButton(
            onPressed: () {
              print('清空失效商品');
              setState(() {
                _expireSourceList.clear();
              });
            },
            style: OutlinedButton.styleFrom(
              backgroundColor: EsColors.White,
              padding: EdgeInsets.zero,
              minimumSize: Size(88, 24),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12)),
              side: BorderSide(color: EsColors.BackGround, width: 1),
            ),
            child: Text(
              '清空失效商品',
              style: TextStyle(
                  color: EsColors.Content,
                  fontSize: EsSizes.XS,
                  fontWeight: EsFontWeights.Normal),
            )),
        SizedBox(height: 15),
      ]),
    );
  }

  /// 失效商品item
  Widget _expireGoods() {
    return Stack(children: [
      Padding(
        padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
                padding: const EdgeInsets.fromLTRB(4, 1, 4, 2),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: EsColors.TitleSecondary,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  '下架',
                  style: TextStyle(
                      color: EsColors.White,
                      fontSize: EsSizes.XXS,
                      fontWeight: EsFontWeights.Normal),
                )),
            SizedBox(width: 8),
            CachedImage(
                width: 80,
                height: 80,
                margin: EdgeInsets.fromLTRB(0, 10, 8, 12),
                scale: BoxFit.cover,
                path:
                    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.szthks.com%2Flocalimg%2F687474703a2f2f6777312e616c6963646e2e636f6d2f62616f2f75706c6f616465642f69372f5431674d4b334663566258585858585858585f2121302d6974656d5f7069632e6a7067.jpg&refer=http%3A%2F%2Fwww.szthks.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633077361&t=7d068084a4534ca36dd2682e1d0d1df0'),
            SizedBox(width: 8),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    '养乐多活菌型乳酸菌饮料品100ml养乐多活菌型乳酸菌饮料品100ml*5',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: EsColors.TitleSecondary,
                        fontSize: EsSizes.MD,
                        fontWeight: EsFontWeights.Normal),
                  ),
                  Text(
                    '经典6个装',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: EsColors.TitleSecondary,
                        fontSize: EsSizes.SM,
                        fontWeight: EsFontWeights.Normal),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 18),
                    child: RichText(
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      text: TextSpan(
                          text: '￥',
                          style: TextStyle(
                              fontSize: EsSizes.XXS,
                              color: EsColors.TitleSecondary,
                              fontWeight: EsFontWeights.Normal),
                          children: <TextSpan>[
                            TextSpan(
                                text: '19.00',
                                style: TextStyle(
                                    fontSize: EsSizes.LG,
                                    color: EsColors.TitleSecondary,
                                    fontWeight: EsFontWeights.Medium)),
                          ]),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
      Positioned(
          left: 0,
          right: 0,
          top: 0,
          bottom: 0,
          child: DecoratedBox(
            decoration: BoxDecoration(color: EsColors.White.withOpacity(0.8)),
          ))
    ]);
  }

  /// 结算部分
  Widget _bottom() {
    return Container(
      decoration: EsDecoration.BoxShadowDefault,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(bottom: 10),
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _selectAll = !_selectAll;
                        for (var item in _goodsSourceList) {
                          item['isSelect'] = _selectAll;
                        }
                      });
                      print(_selectAll ? '全选' : '全取消');
                    },
                    child: Row(
                      children: [
                        Padding(
                          padding: const EdgeInsets.only(left: 8),
                          child: Image(
                            image: AssetImage(_selectAll
                                ? 'assets/images/selectIcon1.png'
                                : 'assets/images/select1.png'),
                            width: 48.w,
                          ),
                        ),
                        Text(
                          '全选',
                          style: TextStyle(
                              color: EsColors.Content,
                              fontWeight: EsFontWeights.Normal,
                              fontSize: EsSizes.MD),
                        )
                      ],
                    ),
                  ),
                  Expanded(child: SizedBox()),
                  Visibility(
                    visible: !_edit,
                    child: Text(
                      '不含运费',
                      style: TextStyle(
                          fontSize: EsSizes.XS,
                          color: EsColors.ContentSecondary,
                          fontWeight: EsFontWeights.Normal),
                    ),
                  ),
                  SizedBox(width: 4),
                  Visibility(
                    visible: !_edit,
                    child: RichText(
                      // textAlign: TextAlign.center,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      text: TextSpan(
                          text: '共',
                          style: TextStyle(
                              fontSize: EsSizes.MD,
                              color: EsColors.TitleSecondary,
                              fontWeight: EsFontWeights.Normal),
                          children: <TextSpan>[
                            TextSpan(
                                text: '￥',
                                style: TextStyle(
                                    fontSize: EsSizes.SM,
                                    color: EsColors.Primary,
                                    fontWeight: EsFontWeights.Normal)),
                            TextSpan(
                                text: '429990.00',
                                style: TextStyle(
                                    fontSize: EsSizes.LG,
                                    color: EsColors.Primary,
                                    fontWeight: EsFontWeights.Medium)),
                          ]),
                    ),
                  ),
                  SizedBox(width: 4),
                ],
              ),
            ),
          ),
          SizedBox(width: 4),
          TextButton(
              style: TextButton.styleFrom(
                  minimumSize: Size(100, 55),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(0)),
                  ),
                  backgroundColor: EsColors.Primary),
              onPressed: () {
                print('结算');
                Get.toNamed(RouteConfig.settleAccounts);
              },
              child: Text(
                _edit ? '删除(1)' : '结算(1)',
                style: TextStyle(
                    fontSize: EsSizes.LG,
                    color: EsColors.White,
                    fontWeight: EsFontWeights.Normal),
              ))
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
